import React, {useCallback, useEffect, useState} from 'react';
import { observer } from 'mobx-react';
import envServerStore from "../store/envServerStore";
import {ExTable} from "../../../common/EditTable";
import {Popconfirm, Space} from "antd";
import {CheckOutlined, CloseOutlined} from "@ant-design/icons";

const EnvServerList = ({envId}) => {
    const {
        findEnvServerList,
        deleteEnvServer,
        updateEnvServer,
        createEnvServer,
        setList,
        envServerList
    } = envServerStore

    const columns = [
        {
            title: '服务名称',
            dataIndex: 'name',
            key: 'name',
            width: "30%",
            ellipsis: true,
            editable: true,
        },
        {
            title: '服务地址',
            dataIndex: 'url',
            key: 'url',
            editable: true,
            width: "50%",
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: "20%",
            render: (_, record) => operation(record, dataSource)
        },
    ];

    const [dataSource, setDataSource] = useState([]);
    const [newRowAction, setNewRowAction] = useState(false);

    const loadData = useCallback(async () => {
        if(envId){
            let list = await findEnvServerList({envId})
            setDataSource(list)
        }else {
            setDataSource([])
            setList([{id:"InitNewRowId"}])
        }
    }, [envId, findEnvServerList]);

    useEffect(async ()=> {
        loadData()
    },[loadData])


    /**
     * 保存表格行数据
     * @param {Object} row - 行数据
     */
    const handleSave = (row) => {
        const newData = [...envServerList];
        const index = newData.findIndex((item) => row.id === item.id);

        if (index > -1) {
            newData.splice(index, 1, { ...newData[index], ...row });
            setList(newData);
        }

        // 如果是新行操作，显示操作按钮
        if (row.id === "InitNewRowId") {
            setNewRowAction(true);
        }
    };

    /**
     * 创建新环境变量
     * @param {Object} values - 表单值
     */
    const onCreated = async (values) => {
        // 只有id的空行不处理
        if (Object.keys(values).length === 1) {
            return null;
        }

        // 删除临时ID，后台会自行创建id
        const { id, ...restValues } = values;

        try {
            await createEnvServer({ ...restValues, envId });
            await loadData();
        } catch (error) {
            console.error('创建环境变量失败:', error);
        }

        setNewRowAction(false);
    };

    /**
     * 更新环境变量
     * @param {Object} value - 表单值
     */
    const handleUpdate = async (value) => {
        try {
            await updateEnvServer(value);
            await loadData();
        } catch (error) {
            console.error('更新环境变量失败:', error);
        }
    };

    /**
     * 取消新建操作
     */
    const onCancel = () => {
        setNewRowAction(false);
        // 重新加载数据，恢复原始状态
        loadData();
    };

    /**
     * 检查记录是否已被修改
     * @param {Object} record - 当前行数据
     * @param {Array} data - 全部数据源
     * @returns {JSX.Element|null} - 渲染更新按钮或null
     */
    const renderUpdateButton = (record, data) => {
        if (!data) return null;

        const originalRecord = data.find(item => item.id === record.id);
        if (!originalRecord) return null;

        // 检查是否有变更
        const isChanged =
            originalRecord.name !== record.name ||
            originalRecord.url !== record.url

        return isChanged ? (
            <svg
                className="icon-s table-edit-icon"
                aria-hidden="true"
                onClick={() => handleUpdate(record)}
            >
                <use xlinkHref="#icon-btn_confirm" />
            </svg>
        ) : null;
    };

    /**
     * 表格操作列渲染
     * @param {Object} record - 行数据
     * @param {Array} data - 全部数据源
     * @returns {JSX.Element} - 操作按钮
     */
    const operation = (record, data) => {
        if (record.id === 'InitNewRowId') {
            return (
                <div className={newRowAction ? "table-row-action-show" : "table-row-action-hidden"}>
                    <Space>
                        <CheckOutlined onClick={() => onCreated(record)} />
                        <CloseOutlined onClick={onCancel} />
                    </Space>
                </div>
            );
        }

        return (
            <Space key={record.id}>
                {renderUpdateButton(record, data)}
                <Popconfirm
                    title="确定删除？"
                    onConfirm={async () => {
                        try {
                            await deleteEnvServer(record.id);
                            await loadData();
                        } catch (error) {
                            console.error('删除环境变量失败:', error);
                        }
                    }}
                    okText='确定'
                    cancelText='取消'
                >
                    <svg className="icon-s table-edit-icon" aria-hidden="true">
                        <use xlinkHref="#icon-shanchu3" />
                    </svg>
                </Popconfirm>
            </Space>
        );
    };


    return (
        <div className='pi-env-table-box'>
            <ExTable
                dataSource={envServerList}
                columns={columns}
                handleSave={handleSave}
            />
        </div>
    );
};

export default observer(EnvServerList);
